import os
import time
import json
import random
import re

from django.views import View
from rest_framework.views import APIView
from rest_framework.response import Response
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect

from mydjango.settings import Django_URL, Vue_URL, UPLOAD_ROOT

from .utils import chack_token, make_token, r0, make_password

from .models import User,Deal, RechargeOrder

from .spider_exchange import getexchange

from celery.task import task

#导入dwebsocket的库
from dwebsocket.decorators import accept_websocket

from apscheduler.schedulers.background import BackgroundScheduler
from django_apscheduler.jobstores import DjangoJobStore, register_events, register_job

from .My_Queue import BuyQueue

import paypalrestsdk

from django.shortcuts import redirect

socket_dict = {}
@accept_websocket
def exchange(request):
    print("链接")
    
    if request.is_websocket():

        while 1:
            # 获取Vue发送的uid
            message = request.websocket.wait()

            if not message:

                break
            else:
                socket_dict[message] = request.websocket

      
# 实例化调度器
scheduler = BackgroundScheduler()
# 调度器使用默认的DjangoJobStore()
scheduler.add_jobstore(DjangoJobStore(), 'defaults')

# 每天隔一分钟执行一次
@register_job(scheduler, 'interval', seconds=1000)
def test():
    # 具体要执行的代码
    res = getexchange()
    data = json.dumps(res)
    for key,value in socket_dict.items():
        value.send(data)
    



# 注册定时任务并开始
register_events(scheduler)
scheduler.start()



# 卖出接口
class SellApi(APIView):
    
    def post(self, request):
        """卖出首先先存入队列中，等待有买的话取出交易"""
        num = request.data.get("num")
        type = request.data.get("name")
        uid = request.data.get("uid")
        print(type,num,type,uid)
        if not all([num, type, uid]):
            return Response({"code": 999, "msg": "参数不齐"})
        data = {
            "uid" :uid,
            "num": num,
            "type": type,
        }
        data = json.dumps(data)
        BuyQueue().push(data)
        return Response({"code": 200, "msg": "成功"})


# 买入接口
class BuyApi(APIView):
    
    def post(self, request):
        """买入查看卖出队列中有无卖出的"""
        num = request.data.get("num")
        type = request.data.get("name")
        uid = request.data.get("uid")
        price = request.data.get("price")
        print("price",price)
        print(num,type,uid)
        if not all([num, type, uid]):
            return Response({"code": 999, "msg": "参数不齐"})
        
        # 查看卖出队列中的所有元素
        l = BuyQueue()
        for i in range(l.empty()):
            data = json.loads(l.index(i))
            # 如果有同一类型的证券并且比买的数量大，就形成交易
            if data.get("type") == type and int(data.get("num")) >= int(num):
                deal = Deal(sell_id=data.get("uid"),buy_id=uid,price=price, num=num,type=type)
                deal.save()
                
                # 判断是否卖出了全部如果刚好全部卖出，那就删除这个数据，如果还有剩余就进行修改
                residue = int(data.get("num")) - int(num)
                if residue:
                    new_data = {
                        "uid" :data.get("uid"),
                        "num": residue,
                        "type": type,
                    }
                    data_index = l.update(i, json.dumps(new_data))
                    return Response({"code": 200, "msg": "购买成功"})
                else:
                    l.delete(json.dumps(data))
                    return Response({"code": 200, "msg": "购买成功"})
                        
        return Response({"code": 999, "msg": "目前没有人卖"})
    
    
# Sandbox account = "sb-gpgb03894137@business.example.com"
# Client ID = "AZB5SoOBmSbAoUbiXytVf1V-fzwFWG_JbuhZzceMkP-yq7h4GYCf_f08R8AtWaSTldjbMJ06ZkNeCik-"
# secret = "EGJ2o7JJlQ6CDGCL0kLjXZItuLsUpmal9xI6kKLNMdZK_wLXYWL-VEi4Ua40XeuJy-xn-jxx8BJXAY0E"

class Payment(APIView):
    def get(self,request):
        uid = request.GET.get("uid")
        price = request.GET.get("price")
        paypalrestsdk.configure({
            "mode": "sandbox", # sandbox代表沙盒
            "client_id": "AZB5SoOBmSbAoUbiXytVf1V-fzwFWG_JbuhZzceMkP-yq7h4GYCf_f08R8AtWaSTldjbMJ06ZkNeCik-",
            "client_secret": "EGJ2o7JJlQ6CDGCL0kLjXZItuLsUpmal9xI6kKLNMdZK_wLXYWL-VEi4Ua40XeuJy-xn-jxx8BJXAY0E"
        })

        payment = paypalrestsdk.Payment({
            "intent": "sale",
            "payer": {"payment_method": "paypal"},
            "redirect_urls": {
                "return_url": "http://192.168.1.65:8000/myapp/paycallback/",#支付成功跳转页面
                "cancel_url": "http://192.168.1.65:8080/recharge/?code=999"},#取消支付页面
            "transactions": [{
                "amount": {
                    "total": "5.00",
                    "currency": "USD"},
                "description": "这是一个订单测试"}]})

        if payment.create():
            print("付款成功创建")
            print(payment.links)
            for link in payment.links:
                if link.rel == "approval_url":
                    token = re.findall(r'token=(.*)',link.href)[0]
                    print(token)
                    # EC-2JA50122WP456123R
                    order_obj = RechargeOrder(uid=uid, price=price,token=token)
                    order_obj.save()
                    approval_url = str(link.href)
                    print(approval_url)
                    return redirect(approval_url)
        else:
            print(payment.error)
            return HttpResponse("支付失败")
        
        
class Paypalcallback(APIView):
    
    def get(self, request):
        print(111111)
        paymentid = request.GET.get("paymentId")
        payerid = request.GET.get("PayerID")
        token = request.GET.get("token")
        print("tokne",token)
        print(paymentid,payerid)
        payment = paypalrestsdk.Payment.find(paymentid)
        
        if payment.execute({"payer_id": payerid}):
            order_obj = RechargeOrder.objects.filter(token=token).first()
            order_obj.state = 1
            order_obj.paymentid = paymentid
            order_obj.payerid = payerid
            print("order_uid",order_obj.uid)
            order_obj.save()
            user_obj = User.objects.filter(pk=order_obj.uid).first()
            print("useronj",user_obj)
            user_obj.balance += float(order_obj.price)
            user_obj.save()
            print("成功")
            
            return redirect("http://192.168.1.65:8080/callback/?code=200")
        else:
            print("失败")
            order_obj = RechargeOrder.objects.filter(token=token).first()
            order_obj.state = 0
            order_obj.paymentid = paymentid
            order_obj.payerid = payerid
            order_obj.save()
            return redirect("http://192.168.1.65:8080/callback/?code=999")


class UploadBurstFile(APIView):
    def post(self,request):
        print(">>>",request)
        
        file = request.FILES.get("file")
        # 获取唯一标识符
        task = request.data.get("identifier")
        chunk = request.data.get("chunkNumber")
        print(task, chunk)
        filename = chunk + task
        contents = file.read()
        with open(os.path.join(UPLOAD_ROOT,filename), "wb") as f:
            f.write(contents)
        print(filename)
        return Response({"filename": filename, "task": task})
    
    
class UploadFile(APIView):
    def post(self, request):
        print("diergejikou111111")
        target_filename = request.data.get("filename")
        task = request.data.get("identifier")
        chunk = 1    # 分片序号
        with open(os.path.join(UPLOAD_ROOT,str(task)+str(chunk)), "wb") as target_f:
            while 1:
                try:
                    filename = os.path.join(UPLOAD_ROOT,str(target_filename))
                    #按照序列打开分片
                    source_file = open(filename, "rb")
                    # 读取分片内容写入新文件
                    target_f.write(source_file.read())
                    source_file.close()
                except IOError as e:
                    print(e)
                    break
                chunk += 1
                print(">>>>>>>>>>>>>>>>>>>",chunk)
                os.remove(filename)
        
        return Response({"code": 200})
